<template>
  <el-button type="primary" @click="showOrderModel">自动下单</el-button>

  <el-table :data="tableData" style="width: 100%" v-loading="loading">
    <el-table-column fixed prop="goods_i.goods_name" label="商家名" align="center" />

    <el-table-column label="商品图" align="center">
      <template #default="scope">
        <el-image style="width: 100px; height: 100px; border-radius: 50%"
          :src="formatUrl(scope.row.goods_i.goods_images)" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
          :initial-index="4" fit="cover" />
      </template>
    </el-table-column>
    <el-table-column prop="goods_i.goods_price" label="价格" align="center" />

    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-link type="primary" @click="onModel(scope.row)">下单</el-link>
        <el-link type="primary" style="margin-left: 15px" @click="onModelCar(scope.row)">加入购物车</el-link>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="dialogVisible" title="下单" width="600">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" status-icon>
      <el-form-item label="请输入下单价格" prop="pay_price">
        <el-input type="number" v-model="ruleForm.pay_price" />
      </el-form-item>
      <el-form-item label="请输入下单数量" prop="order_num">
        <el-input type="number" v-model="ruleForm.order_num" />
      </el-form-item>
      <el-form-item label="请输入下单利润" prop="order_profile">
        <el-input type="number" v-model="ruleForm.order_profile">
          <template #append>%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="到货时间" prop="arrival_time">
        <el-date-picker v-model="ruleForm.arrival_time" type="datetime" placeholder="请选择到货时间"
          format="YYYY/MM/DD HH:mm:ss" value-format="YYYY/MM/DD HH:mm:ss" />
      </el-form-item>
      <el-form-item label="下单">
        <el-radio-group v-model="radioOrder">
          <el-radio value="1" size="large">立即下单</el-radio>
          <el-radio value="2" size="large">定时下单</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="下单时间" v-if="radioOrder == '2'" prop="order_time">
        <el-date-picker v-model="ruleForm.order_time" type="datetime" placeholder="请选择下单时间"
          format="YYYY/MM/DD HH:mm:ss" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm"> 下单 </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisibleCar" title="下单" width="600">
    <el-form ref="ruleFormCarRef" style="max-width: 600px" :model="carData" label-width="auto" class="demo-ruleForm"
      status-icon>
      <el-form-item label="请输入下单价格" prop="pay_price">
        <el-input type="number" v-model="carData.pay_price" />
      </el-form-item>
      <el-form-item label="请输入下单数量" prop="buy_num">
        <el-input type="number" v-model="carData.buy_num" />
      </el-form-item>
      <el-form-item label="请输入下单利润" prop="order_profile">
        <el-input type="number" v-model="carData.order_profile">
          <template #append>%</template>
        </el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="btnLoading" @click="addCar">
          加入购物车
        </el-button>
        <el-button @click="dialogVisibleCar = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="orderModel" v-loading="loading" title="下单" width="1000">
    <el-form @submit.native.prevent style="max-width: 600px" label-width="auto" class="demo-ruleForm" status-icon>
      <el-form-item label="请输入累计下单金额" prop="pay_price">
        <el-input @keydown.enter.stop="getProducts" type="number" v-model="orderAmountSum">
          <template #append>
            <div @click="getProducts" style="cursor: pointer;">计算</div>
            <!-- <el-button  style="width: 40px;text-align: center;" type="primary" @click="getProducts">  </el-button> -->
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <el-table :data="orderData" v-if="orderData.length" show-summary :summary-method="getSummaries">
      <el-table-column prop="buy_num" label="商品图片" align="center">
        <template #default="scope">
          <img :src="formatUrl(scope.row.goods_i.goods_master_image)" alt="" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>

      <el-table-column prop="productName" label="商品名称" align="center" />
      <el-table-column prop="buy_num" label="商品数量" align="center"></el-table-column>
      <el-table-column prop="pay_price" label="下单价格" align="center"></el-table-column>
      <el-table-column prop="order_price" label="支付价格" align="center"></el-table-column>
      <el-table-column prop="order_profile" label="下单利率" align="center"></el-table-column>
      <!-- <el-table-column prop="osn" label="订单号"></el-table-column> -->
      <el-table-column prop="order_profile" label="操作" align="center">
        <template #default="scope">
          <el-button type="danger" :loading="btnLogin" @click="onDel(scope.row, $index)"
            style="width: 40px;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="btnLogin" type="primary" @click="betchCars">
          批量加入购物车
        </el-button>
        <el-button @click="orderModel = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <carCommponents :getCartList="getCartList" :len="carDatas.length" :data="carDatas"></carCommponents>
</template>

<script lang="ts" setup>
import { GoodsApi } from "~/api/goods";
import { onMounted, reactive, ref } from "vue";
import { formatUrl } from "~/http/http";
import { useRoute } from "vue-router";
import { ElMessage, ElLoading } from "element-plus";
import { h } from "vue";
const btnLogin = ref(false);
const loading = ref(true);
const router = useRoute();
const tableData = ref();
const dialogVisible = ref(false);
const dialogVisibleCar = ref(false);
const good = ref();
const radioOrder = ref("1");
const bok = ref(true);
const btnLoading = ref(false);
const orderModel = ref(false);
const orderAmountSum = ref();
const ruleForm = reactive({
  pay_price: undefined, // 订单价格
  arrival_time: undefined, // 到货时间
  order_profile: undefined, // 下单时间
  order_num: undefined, //下单数量
  order_time: 0,
  store_id: router.query.id,
  goods_id: undefined,
});
const carData = reactive({
  goods_id: "",
  store_id: "",
  buy_num: "",
  order_price: "",
  pay_price: "",
  order_profile: "",
});
const rules = reactive({
  pay_price: [{ required: true, message: "请输入下单价格", trigger: "blur" }],
  order_profile: [
    { required: true, message: "请输入订单利润", trigger: "blur" },
  ],
  order_num: [{ required: true, message: "请输入下单数量", trigger: "blur" }],
});
const carDatas = ref([]);
const orderData = ref([]);
const ruleFormRef = ref();
const getData = async () => {
  const shops = await GoodsApi.getList(router.query.id);
  shops.data.data.map((item: any) => {
    item.goods_i.goods_images = item.goods_i.goods_images.split(",")[0];
    item.price = Number(item.goods_i.goods_price);
  });
  tableData.value = shops.data.data;
  loading.value = false;
};
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h("div", { style: { textDecoration: "underline" } }, [
        "总计",
      ]);
      return;
    }
    const values = data.map((item) => {
      if (column.property == "order_price") {
        return Number(item[column.property]);
      } else {
        return "";
      }
    });
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      })}`;
    } else {
      sums[index] = "N/A";
    }
  });
  sums[4] = h(
    "div",
    { style: { color: "red", fontWeight: "bold", fontSize: "20px" } },
    [sums[4]]
  );
  return sums;
};
const showOrderModel = () => {
  orderAmountSum.value = ''
  orderData.value = []
  orderModel.value = true;
};
// 计算最优结果
const getProducts = async () => {
  
  if (orderAmountSum.value) {
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    const res = await GoodsApi.getProductCombin({ store_id: router.query.id, order_cash: orderAmountSum.value });
    console.log(res.data.data);
    // return 
    // console.time();
    // const bestCombination = findBestProductCombination2(
    //   orderAmountSum.value,
    //   tableData.value
    // );
    // console.timeEnd();
    const bestCombination = res.data.data
    // console.log("最佳商品组合:");
    bestCombination.forEach((item) => {
      item.goods_id = item.goods_id;
      item.store_id = item.store_id;
      item.buy_num = 1;
      item.order_price = item.goods_i.goods_price;
      item.pay_price = item.goods_i.goods_price * 1.5;
      item.order_profile = "10";
      item.productName = item.goods_i.goods_name;
      console.log(`商品名称：${item.productName}, 商品价格：${item.price}`);
    });
    // console.log(
    //   "选择商品总价格:",
    //   bestCombination.reduce((sum, p) => sum + p.price, 0)
    // );
    orderData.value = bestCombination;
    loading.close()
    console.log(orderData.value);
  }
};
const findBestProductCombination2 = (targetAmount: any, products: any) => {
  // 转换为分单位，避免浮点数问题
  const scaledTarget = parseInt(targetAmount);
  const scaledProducts = products.map((p) => ({
    ...p,
    price: parseInt(p.price),
  }));

  // 过滤无效商品（价格必须为正且不超过目标金额）
  const validProducts = scaledProducts.filter(
    (p: any) => p.price > 0 && p.price <= scaledTarget
  );

  if (validProducts.length === 0 || scaledTarget <= 0) {
    return [];
  }

  // 初始化动态规划数组
  const dp = new Array(scaledTarget + 1).fill(0).map(() => ({
    sum: 0,
    products: [],
  }));

  for (const product of validProducts) {
    const price = product.price;
    for (let i = scaledTarget; i >= price; i--) {
      const prev = dp[i - price];
      const newSum = prev.sum + price;
      if (newSum > dp[i].sum && newSum <= scaledTarget) {
        dp[i] = {
          sum: newSum,
          products: [...prev.products, product],
        };
      }
    }
  }

  // 找到最佳组合
  let bestCombination = [];
  let bestSum = 0;
  for (let i = scaledTarget; i >= 0; i--) {
    if (dp[i].sum > bestSum) {
      bestSum = dp[i].sum;
      bestCombination = dp[i].products;
    }
  }

  // 转换回原单位（元）
  return bestCombination;
};
const findBestProductCombination = (targetAmount: any, products: any) => {
  // 过滤掉价格超过目标金额的商品并按价格降序排序
  const validProducts = products
    .filter(p => p.price > 0 && p.price <= targetAmount)
    .sort((a, b) => b.price - a.price);
  let bestCombination = [];
  let bestSum = 0;

  // 遍历商品列表，尝试找到最佳组合
  for (let i = 0; i < validProducts.length; i++) {
    const product = validProducts[i];
    bestSum += product.price;
    if (bestSum > targetAmount) {
      bestSum -= product.price; // 如果超过目标金额，减去当前商品的价格
      continue; // 跳过价格超过目标金额的商品
    }
   

    console.log("当前价格", bestSum);
    bestCombination.push(product);
    if (bestSum == targetAmount) {
      break;
    }
  }
  
  return bestCombination;
};
const onModel = (item: any) => {
  good.value = item;
  ruleForm.pay_price = item.goods_i.goods_price * 1.5;
  ruleForm.order_profile = 10;
  ruleForm.order_num = 1;
  ruleForm.goods_id = item.goods_id;
  dialogVisible.value = true;
  ruleFormRef.value.resetFields();
  radioOrder.value = "1";
};
// 删除商品
const onDel = async (record:any) => {
  btnLogin.value = true;
  orderData.value.forEach((item:any, index) => {
    if (item.id == record.id) {
      console.log(item)
      orderData.value.splice(index, 1);
    }
  });
  btnLogin.value = false;
};
// 批量加入购物车
const betchCars = async () => {
  loading.value = true;
  btnLogin.value = true;
  const arr:any = []
  let obj:any = {}
  orderData.value.forEach((item:any, index) => {
    obj.goods_id = item.goods_id;
    obj.store_id = item.store_id;
    obj.buy_num = 1;
    obj.order_price = item.goods_i.goods_price;
    obj.pay_price = item.goods_i.goods_price * 1.5;
    obj.order_profile = "10";

    arr.push(obj)
    obj = {}
  })
  await GoodsApi.addCartMore({ cart_data: arr });
  // const promises = orderData.value.map((item) => {
  //   return GoodsApi.addCartNew(item);
  // });

  // // 等待所有接口完成
  // const results = await Promise.all(promises);
  getCartList();
  loading.value = false;
  btnLogin.value = false;
  orderModel.value = false
  // console.log("所有接口执行完毕", results);

};
const onModelCar = async (item: any) => {
  loading.value = true;
  carData.goods_id = item.goods_id;
  carData.store_id = item.store_id;
  carData.buy_num = 1;
  carData.order_price = item.goods_i.goods_price;
  carData.pay_price = item.goods_i.goods_price * 1.5;
  carData.order_profile = "10";
  // dialogVisibleCar.value = true
  const res = await GoodsApi.addCartNew(carData);
  loading.value = false;
  if (res) {
    if (res.data.code == 200) {
      ElMessage.success("下单成功");
      getCartList();
    }
  }
};
const addCar = async () => {
  btnLoading.value = true;
  const res = await GoodsApi.addCartNew(carData);
  console.log(res);
  btnLoading.value = false;
  dialogVisibleCar.value = false;
  if (res.code != 200) {
    ElMessage.warning(res.data.msg);
    return false;
  }
  if (res.data.code == 200) {
    ElMessage.success("下单成功");
    getCartList();
  } else {
  }
};
const getCartList = async () => {
  const res = await GoodsApi.getCartList({ store_id: router.query.id });
  carDatas.value = res.data.data.data;
};

const submitForm = async () => {
  if (!ruleFormRef.value) return;
  if (!bok.value) return false;
  bok.value = false;
  await ruleFormRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      if (radioOrder.value == "1") {
        ruleForm.order_time = 0;
      }
      if (ruleForm.order_time) {
        if (new Date(ruleForm.order_time).getTime() <= new Date().getTime()) {
          ElMessage.error("下单时间不能小于当前时间");
          setTimeout(() => {
            bok.value = true;
          }, 2000);
          return false;
        }
      }

      GoodsApi.createOrder(ruleForm).then((res) => {
        dialogVisible.value = false;
        ElMessage.success("下单成功");
        setTimeout(() => {
          bok.value = true;
        }, 2000);
      });
    } else {
      console.log("error submit!", fields);
      setTimeout(() => {
        bok.value = true;
      }, 2000);
    }
  });
};
onMounted(() => {
  getData();
  getCartList();
});
</script>
